﻿<h2>WebSocket</h2>

<div class="form-inline">
    <div class="form-group">
        <label for="count">消息数</label>
        <input type="text" class="form-control" id="count" placeholder="服务端返回的消息数">
    </div>
    <button class="btn btn-primary" onclick="wsTest()">提交</button>
</div>

<blockquote>
    <ol id="msg"></ol>
</blockquote>

@section Foot{
    <script>
        var WsUtil = {
            msg: document.getElementById('msg'),
            ws: null,
            connect: function (url, callback) {
                var _this = this;
                _this.msg.innerHTML = '';
                _this.appendMsg('正在连接......', '#00f');
                _this.ws = new WebSocket(url);
                _this.ws.onopen = function () {
                    _this.appendMsg('客户端已连接', '#00f');
                    if (callback) {
                        callback(_this.ws);
                    }
                }
                _this.ws.onmessage = function (evt) {
                    _this.appendMsg(evt.data);
                }
                _this.ws.onclose = function () {
                    _this.appendMsg('客户端已断开连接', '#00f');
                }
                _this.ws.onerror = function (evt) {
                    _this.appendMsg(evt.data, '#f00');
                }
            },
            close: function () {
                if (this.ws) {
                    this.ws.close();
                    this.ws = null;
                }
            },
            appendMsg: function (message, color) {
                var li = document.createElement('li');
                li.style.color = color || '#000';
                li.innerHTML = message;
                msg.appendChild(li);
            }
        }

        function wsTest() {
            var count = document.getElementById('count').value;
            var url = 'ws://@Request.Url.DnsSafeHost:@Request.Url.Port/html5/wstask?count=' + count;
            WsUtil.connect(url, function (ws) {
                ws.send('test');
            });
        }
    </script>
}